package isquirrel.servlets;

import isquirrel.Lastfm;
import isquirrel.beans.Interest;
import isquirrel.beans.User;
import isquirrel.error.CannotLoginUserException;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import net.roarsoftware.lastfm.Artist;
import net.roarsoftware.lastfm.ImageSize;

import org.json.JSONException;
/**
 * Servlet implementation class Music
 */
public class Music extends HttpDBServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Music() {
        super();
    }

	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
	}

	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
		User u = getLoggedInUser();
		int latest = Integer.valueOf((String)request.getParameter("latest"));
		
		ArrayList<String> keywords = new ArrayList<String>();
		if (latest > 0){
			int i = 0;
			Iterator<Interest> it = u.getInterests().iterator();
			while (i < 4 ){
				String keyword = "";
				if (Math.random() > 0.6 && u.hasKeywords()) {keyword = u.getKeyword();}
				else {
					int rnd = (int) Math.floor(Math.random() * (u.getInterests().size()));
					if (rnd == 0 ) keyword = it.next().getLabel();
					else{
						while (rnd > 0){
							keyword = it.next().getLabel();
							--rnd;
						}
					}
				}
				keywords.add(keyword);
				it = u.getInterests().iterator();
				++i;
			}	
		}
		else{
			Iterator<Interest> iterator = u.getInterests().iterator();
			while (iterator.hasNext()){
			
				keywords.add(iterator.next().getLabel());
			
			}
		}
		
		Lastfm lastfm = new Lastfm();
		//HashMap<String, Collection<Artist>> artistRecommendations = lastfm.getArtistsByKeywords(keywords, 4);
		Collection<Artist> artistRecommendations = lastfm.getArtistsByKeywords(keywords, 0, 12);
		if (artistRecommendations == null || artistRecommendations.size() == 0) {
			response.getWriter().print("<div> We haven't been able to find any artists that might match your interests</div>");
		}
		else {
			PrintWriter out = response.getWriter();
			
			if (request.getParameter("viewmore") != null && ((String)request.getParameter("viewmore")).equals("t")){
				response.getWriter().println("<div id='rec_music_content_changeable'>");
			}
			
			String style = "style='display:none' ";
			if (latest == 0){
				style = "";
			}
			response.getWriter().println("<div "+ style + "id='rec_music_page_" + latest+ "'>");
			for (Artist artist : artistRecommendations) {
				//Collection<Artist> artistKeyword = artistRecommendations.get(s);
				int musicindex = 0;
				if (artist == null) {
					continue;
				}else {
						++musicindex;
						String mclass = "'lastfmcontainer'";
						if (musicindex % 4 == 0){
							mclass = "'lastfmcontainer norightmargin'";
						}
						out.print("<div class=" + mclass + ">" +
									"<div style='height:115px;overflow:hidden'>" +
									"<img onClick='window.open(\""+artist.getUrl()+"\");' onMouseOver='window.musichighlight(this);' onMouseOut='window.musicunhighlight(this);' class='musicthumb' src='"  +
									(artist.getImageURL(ImageSize.LARGE) == null || artist.getImageURL(ImageSize.LARGE).equals("") ? "/"+request.getRequestURI().split("/")[1]+"/images/no_photo.png" :artist.getImageURL(ImageSize.LARGE)) + "' />" +
									"</div>" + 
								"<div class='videodetails'>" + 
								"<div class='videotitle'>" +
									artist.getName()+ 
									"</div>" +
									"</div>" +
						"</div>");
					}
			}
		}
			response.getWriter().println("</div>"); //close pagelet 
			if (request.getParameter("viewmore") != null && ((String)request.getParameter("viewmore")).equals("t")){
				response.getWriter().print("</div>"); //close content changeable -- this is shown only once
				response.getWriter().print("<div id='music_viewmore' onClick='window.viewmore(\"Music\")' class='viewmore clickable'> View more </div>");
			}
	}
		

}
